package fr.cephb.locustree;

import java.io.IOException;
import java.io.Serializable;

import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;

import fr.cephb.berkeleydb.binding.JSONBinding;
import fr.cephb.json.JSONBuilder;
import fr.cephb.json.JSONable;

public class Track
	implements Serializable,JSONable
	{
	private static final long serialVersionUID = 1L;
	private Integer id;
	private String name;
	private String description;
	private Object json;
	//private Class<Displayer> displayer;
	int end_resolution=10;
	int start_resolution=10000000;

	public static class Binding
		extends TupleBinding<Track>
		{
		private JSONBinding jsonBinding=new JSONBinding();
		@Override
		public Track entryToObject(TupleInput in)
			{
			Track t= new Track(in.readInt(),in.readString());
			t.description=in.readString();
			t.start_resolution=in.readInt();
			t.end_resolution=in.readInt();
			t.setObject(jsonBinding.entryToObject(in));
			return t;
			}
		@Override
		public void objectToEntry(Track o, TupleOutput out)
			{
			out.writeInt(o.getId());
			out.writeString(o.getName());
			out.writeString(o.description);
			out.writeInt(o.start_resolution);
			out.writeInt(o.end_resolution);
			this.jsonBinding.objectToEntry(o.getObject(), out);
			}
		}
	
	public Track(int id,String  name)
		{
		this.id=id;
		this.name=name;
		this.description=this.name;
		}
	
	
	public String getName()
		{
		return name;
		}
	
	public void setDescription(String description)
		{
		this.description = description;
		}
	
	public String getDescription()
		{
		return description;
		}
	
	public Integer getId()
		{
		return id;
		}
	
	public Object getObject()
		{
		return json;
		}
	public void setObject(Object json)
		{
		this.json = json;
		}
	
	@Override
	public int hashCode()
		{
		final int prime = 31;
		int result = 1;
		result = prime * result + id.hashCode();
		return result;
		}
	
	@Override
	public boolean equals(Object obj)
		{
		if (this == obj) return true;
		if (obj == null) return false;
		if (getClass() != obj.getClass()) return false;
		Track other = (Track) obj;
		if (!id.equals(other.id)) return false;
		return true;
		}
	
	@Override
	public String toJSON()
		{
		return new JSONBuilder().
			put("name", getName()).
			put("description", getDescription()).
			put("id", getId()).
			put("metadata", getObject()).
			getString();
		}
	
	public String getMetadataAsJson() throws IOException
		{
		return new JSONBuilder().toString(getObject());
		}
	
	
	@Override
	public String toString()
		{
		return toJSON();
		}
	}
